package com.ycrlkj.android.modulescore.main.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.navi.NaviSetting;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.ycrlkj.android.modulesbase.libbase.utils.Logger;
import com.ycrlkj.android.modulescore.main.BR;
import com.ycrlkj.android.modulescore.main.R;
import com.ycrlkj.android.modulescore.main.apiservice.FreightOrderApiService;
import com.ycrlkj.android.modulescore.main.databinding.ActivityOnlineFreightOrderListBinding;
import com.ycrlkj.android.modulescore.main.entity.FreightOrder;
import com.ycrlkj.android.modulescore.main.entity.Query.FreightOrderQuery;
import com.ycrlkj.android.modulespublic.common.base.DataBindingRecyclerViewAdapter;
import com.ycrlkj.android.modulespublic.common.constant.RoutePath;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiExceptionHandler;
import com.ycrlkj.android.modulespublic.common.net.exception.ErrorConsumer;
import com.ycrlkj.android.modulespublic.common.net.transformer.ResponseTransformer;
import com.ycrlkj.android.modulespublic.common.utils.xpopup.XPopupUtil;
import com.ycrlkj.android.modulespublic.common.widget.titlebar.MTitleBar;

import java.util.List;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import lombok.SneakyThrows;
import pub.devrel.easypermissions.EasyPermissions;

@AndroidEntryPoint
@Route(path = RoutePath.PAGE_ONLINE_FREIGHT_ORDER_LIST)
public class OnlineFreightOrderListActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    @Inject
    FreightOrderApiService freightOrderApiService;

    private ActivityOnlineFreightOrderListBinding binding;

    private RecyclerView recyclerView;

    private DataBindingRecyclerViewAdapter<FreightOrder> adapter;

    private AMapLocationClient aMapLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityOnlineFreightOrderListBinding.inflate(getLayoutInflater());

        setContentView(binding.getRoot());

        initTitleBar();
        initAdapter();

        initPermissions();

        getAllOnline();
    }

    public void initAdapter() {
        recyclerView = binding.recyclerView;
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new DataBindingRecyclerViewAdapter<>(this, R.layout.item_online_freight_order, BR.freightOrder, R.id.btn_toDetail, new DataBindingRecyclerViewAdapter.OnItemChildClickListener<FreightOrder>() {
            @Override
            public void onItemChildClickListener(FreightOrder item, int position) {
                String id = item.getId();
                Double locationDistance = item.getLocationDistance();
                if(locationDistance == null)
                    locationDistance = 0d;
                ARouter.getInstance().build(RoutePath.PAGE_ONLINE_FREIGHT_ORDER_DETAIL).withString("id", id).withDouble("locationDistance", locationDistance).navigation();
            }
        });
        recyclerView.setAdapter(adapter);
    }

    @SuppressLint("CheckResult")
    public void getAllOnline() {
        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(this);
        XPopupUtil.hideLoadingDelay(loadingPopupView);

        FreightOrderQuery freightOrderQuery = new FreightOrderQuery();

        freightOrderApiService.getAllOnline(freightOrderQuery)
                .compose(ResponseTransformer.obtain())
                .subscribe(freightOrders -> {

                    //为每个订单计算当前定位与发货点的距离
                    initAMapLocationListener(freightOrders);

                    adapter.add(freightOrders);

                    XPopupUtil.hideLoading(loadingPopupView);
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        XPopupUtil.hideLoading(loadingPopupView);
                        ApiExceptionHandler.doWith(OnlineFreightOrderListActivity.this, e);
                    }
                });

    }


    public void initAMapLocationListener(List<FreightOrder> freightOrders) {
        AMapLocationListener aMapLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {

                if (aMapLocation.getErrorCode() != 0) {
                    Logger.e("获取定位失败, " + aMapLocation.getErrorInfo());
                    ToastUtils.showLong("获取定位失败, " + aMapLocation.getErrorInfo());
                    return;
                }

                int locationType = aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表

                Double locationLat = aMapLocation.getLatitude();//获取纬度
                Double locationLng = aMapLocation.getLongitude();//获取经度

                freightOrders.forEach(freightOrder -> setLocationDistance(freightOrder, locationLat, locationLng));

                //停止定位(只定位一次)
                aMapLocationClient.stopLocation();
            }
        };

        try {
            NaviSetting.updatePrivacyShow(this, true, true);
            NaviSetting.updatePrivacyAgree(this, true);

            aMapLocationClient = new AMapLocationClient(getApplicationContext());

            aMapLocationClient.setLocationListener(aMapLocationListener);

            AMapLocationClientOption option = new AMapLocationClientOption();
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
            option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
            //获取一次定位结果, 默认为false
            option.setOnceLocation(true);
            //是否返回地址信息（默认true）
            option.setNeedAddress(true);
            //设置定位间隔,单位毫秒,默认为2000ms
            //option.setInterval(2000);

            //给定位客户端对象设置定位参数
            aMapLocationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            aMapLocationClient.stopLocation();

            //启动定位
            aMapLocationClient.startLocation();
        }catch(Exception e){
            ToastUtils.showLong("定位失败");
            e.printStackTrace();
        }

    }


    @SneakyThrows
    public void setLocationDistance(FreightOrder freightOrder, Double locationLat, Double locationLng) {
        RouteSearch.OnRouteSearchListener onRouteSearchListener = new RouteSearch.OnRouteSearchListener() {
            //驾车路线回调
            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int errorCode) {
                if (errorCode == 1000) {
                    if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                        if (driveRouteResult.getPaths().size() > 0) {
                            final DrivePath drivePath = driveRouteResult.getPaths().get(0);

                            int dis = (int) drivePath.getDistance();
                            Double locationDistance = dis / 1000d;
                            locationDistance = (double) Math.round(locationDistance * 10) / 10; //此操作为使double保留1位小数
                            freightOrder.setLocationDistance(locationDistance);

                        } else if (driveRouteResult.getPaths() == null) {
                            ToastUtils.showLong("未找到路线");
                        }
                    } else {
                        ToastUtils.showLong("获取到路线失败");
                    }
                } else {
                    ToastUtils.showLong("请求获取路线失败");
                }
            }

            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
            }
        };

        RouteSearch routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(onRouteSearchListener);

        Double startLat = freightOrder.getStartLat();
        Double startLng = freightOrder.getStartLng();

        if (startLat == null || startLng == null) {
            //Logger.e("坐标不全, 无法计算距离");
            freightOrder.setLocationDistance(0d);
            return;
        }

        LatLonPoint startPoint = new LatLonPoint(startLat, startLng);
        LatLonPoint locationPoint = new LatLonPoint(locationLat, locationLng);
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, locationPoint);

        // 起点终点，驾车模式:0=>速度优先，途径点（最多支持6个），避让区域（最多支持32个），避让道路
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, 0, null, null, "");
        routeSearch.calculateDriveRouteAsyn(query);// 异步路线规划驾驶模式查询
    }

    /* #region ========================= 权限管理 开始 ====================== */
    public void initPermissions() {
        //定位需要申请的权限
        String[] perms = {
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.READ_PHONE_STATE
        };

        if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
            Logger.e("已获取定位权限");
        } else {
            EasyPermissions.requestPermissions(this, "必要的权限", 0, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Logger.e("定位请求成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Logger.e("定位请求失败");
    }
    /* #endregion ====================== 权限管理 结束 ====================== */


    public void initTitleBar() {
        MTitleBar titleBar = binding.mTitleBar;
        titleBar.setBtnEvents(new MTitleBar.BtnEvents() {
            @Override
            public void setBtnLeftOnClickListener() {
                OnlineFreightOrderListActivity.this.finish();
            }

            @Override
            public void setBtnRightOnClickListener() {
            }
        });
    }

}